<template>
  <div class="pane-account">
    <el-form
      label-width="60px"
      :model="account"
      :rules="accountRules"
      status-icon
      ref="formRef"
    >
      <el-form-item label="账号" prop="name">
        <el-input v-model="account.name"/>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="account.password" show-password />
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormRules, ElForm } from 'element-plus'
import useLoginStore from '@/store/login/login'
import type { IAccount } from '@/types'
import { localCache } from '@/utils/cache'

const CACHE_NAME = 'name'
const CACHE_PASSWORD = 'password'

const loginStore = useLoginStore()

const account = reactive<IAccount>({
  name: localCache.getCache(CACHE_NAME) ?? '',
  password: localCache.getCache(CACHE_PASSWORD) ?? ''
})

//定义校验规则
const accountRules: FormRules = {
  name: [
    { required: true, message: '请输入账号~', trigger: 'blur'},
    { pattern: /^[a-z0-9]{4,11}$/, message: '账号由字母或数字组成4~11位长度', trigger: 'blur'}
  ],
  password: [
    { required: true, message: '请输入密码~', trigger: 'blur'},
    { pattern: /^[a-z0-9]{6,12}$/, message: '密码由字母或数字组成6~12位长度', trigger: 'blur'}
  ]
}


const formRef = ref<InstanceType<typeof ElForm>>()
function loginAction(isRemPwd: boolean) {
  formRef.value?.validate(valid => {
    if(valid) {
      //验证上面的规则是否成功
      // console.log('验证成功')
      // console.log('拿到账号密码',account.name,account.password)

      const name = account.name
      const password = account.password
      
      loginStore.loginAccountAction({name, password}).then(res => {
        //判断是否需要记住密码
        if(isRemPwd) {
          localCache.setCache(CACHE_NAME, name)
          localCache.setCache(CACHE_PASSWORD, password)
        }else {
          localCache.removeCache(CACHE_NAME)
          localCache.removeCache(CACHE_PASSWORD)
        }
      })
      
      ElMessage({
        message: `账号${name}密码${password}`,
        type: 'success',
      })
    }else {
      ElMessage.error('请输入正确的用户格式')
    }
  })
  
}

/**
 * 将要传递的信息暴露出去 父组件通过ref绑定子组件 .value的形式调用这里面的函数
 */
defineExpose({
  loginAction
})

</script>

<style scoped lang="less">

</style>